package com.andy.common.parser;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.TreeTraversingParser;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import com.fasterxml.jackson.dataformat.yaml.YAMLParser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;

/**
 * Created by Administrator on 2017/9/4.
 */
public class YamlParse<T> {
    private static final Logger LOG = LoggerFactory.getLogger(YamlParse.class);
    private YAMLFactory yamlFactory;
    private ObjectMapper objectMapper;
    private Class<T> clazz;

    public YamlParse(Class<T> clazz) {
        this.yamlFactory = new YAMLFactory();
        this.objectMapper = new ObjectMapper();
        this.clazz = clazz;
    }

    /**
     * parse yml file to entity
     *
     * @param path
     * @return
     */
    public T parser(String path) {
        InputStream fis;
        fis = YamlParse.class.getClassLoader().getResourceAsStream(path);
        if (fis == null) {
            LOG.error("Can not find config file: {}.", path);
            return null;
        }
        try {
            objectMapper.enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
            YAMLParser yamlParser = yamlFactory.createParser(fis);
            JsonNode node = objectMapper.readTree(yamlParser);
            TreeTraversingParser treeTraversingParser = new TreeTraversingParser(node);
            T config = objectMapper.readValue(treeTraversingParser, clazz);
            return config;
        } catch (IOException e) {
            LOG.error("Error parsing config file: " + path, e);
        } catch (Exception e) {
            LOG.error("Error parsing config file: " + path, e);
        }
        return null;
    }
}
